package com.chunyu.app.utils;

import org.apache.commons.codec.binary.Base64;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;

public class Base64Utils {
	private static final String CHARSET = "UTF-8";
	private static final Logger logger = LoggerFactory.getLogger(Base64Utils.class);

	public static String encode(byte[] value) throws Exception {
		try {
			return new String(Base64.encodeBase64(value), CHARSET);
		} catch (Exception e) {
			logger.error("encode", e);
			throw e;
		}
	}

	public static String encode(String value) throws Exception {
		return encode(value.getBytes(CHARSET));
	}

	public static String decode(String value) throws Exception {
		try {
			if (Base64.isBase64(value)) {
				return new String(Base64.decodeBase64(value), CHARSET);
			} else {
				return value;
			}
		} catch (Exception e) {
			logger.error("encode", e);
			throw e;
		}
	}
}
